module Session
  
  def authenticate(logon, password)
    User.first(:conditions => {:email => logon, :password => Digest::MD5.hexdigest(password), :active => true})
  end 
  
  def self.included(klass)
    klass.class_eval do
      include AuthorizationHelpers
    end
  end
  
  module AuthorizationHelpers
    
    def current_user
      begin
        @current_user ||= User.find(session[:user_id])
      rescue
        return false
      end
    end
    
    def user_logged?
      return session[:user_id] && current_user 
    end
    
    def check_user_logged
      respond_to do |format|
        format.html do
          unless user_logged?
            flash[:notice] = I18n.t(:you_are_not_logged_in, :scope => :authorization)
            session[:return_to] = request.request_uri
            redirect_to login_url
          end
        end
        format.js do
          unless user_logged?
            user = authenticate_or_request_with_http_basic do |login, password|
              session[:user_id] = authenticate(login, password)
            end
          end
        end
      end
      set_current_user_in_thread
    end
    
    def set_current_user_in_thread
      Thread.current[:user_id] = current_user.id
    end
    
  end
end